﻿using AntUnion.FrameWork.Model.Models;
using Microsoft.AspNetCore.Cors;
using AntUnion.FrameWork.Web.Extend;
using AntUnion.FrameWork.Web.Filter;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;

namespace AntUnion.FrameWork.Web.Controllers
{
    [EnableCors("AllowCors")]
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    [TypeFilter(typeof(MyExceptionFilter))]
    public class MiniProgramController : BaseController
    {
        private readonly mtContext _context;

        public MiniProgramController(mtContext context) : base(context)
        {
            _context = context;
        }

        string appid = DefaultCache.SystemConfig()["routine_appId"].ToString();
        string appsecret = DefaultCache.SystemConfig()["routine_appsecret"].ToString();

        /// <summary>
        /// 根据js_code返回jscode2session（小程序）
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost, AllowAnonymous]
        public JsonResult Jscode2session(Jscode2sessionReq model)
        {
            Result res = new Result();
            Jscode2session jscode2session = MiniProgramHelper.GetJscode2session(_context,appid, appsecret, model.js_code);
            if (jscode2session.errcode == 0)
            {
                res.Code = 0;
                res.Data = jscode2session;
            }
            else
            {
                throw new Exception(jscode2session.errmsg);
            }
            return new JsonResult(res);
        }

        /// <summary>
        /// 通过微信获取绑定手机
        /// </summary>
        /// <param name="wxPhoneNumber"></param>
        /// <returns></returns>
        //[HttpPost]
        //public JsonResult PhoneNumber(WxPhoneNumber wxPhoneNumber)
        //{
        //    Result res = new Result();
        //    string phone = MiniProgramHelper.GetPhoneNumber(wxPhoneNumber, appid, appsecret);
        //    int uid = MyUser.Uid;
        //    Member member = _context.Members.Where(k => k.Uid == uid).FirstOrDefault();
        //    member.Phone = phone;
        //    _context.SaveChanges();
        //    res.Code = 0;
        //    res.Data = phone;
        //    return new JsonResult(res);
        //}
    }
}
